title: “NVIDIA NIM” description: “Use Weave to trace and log LLM calls made via the ChatNVIDIA library”

Weave는 자동으로 ChatNVIDIA 라이브러리를 통해 이루어진 LLM 호출을 추적하고 기록합니다. ChatNVIDIA 라이브러리를 통해 이루어진 LLM 호출을 weave.init() 호출 후 자동으로 추적하고 기록합니다.
최신 튜토리얼은 Weights & Biases on NVIDIA를 방문하세요.

추적

개발 중이나 프로덕션 환경에서 LLM 애플리케이션의 추적 기록을 중앙 데이터베이스에 저장하는 것이 중요합니다. 이러한 추적 기록은 디버깅에 사용되며, 애플리케이션을 개선하는 동안 평가할 수 있는 까다로운 예제 데이터셋을 구축하는 데 도움이 됩니다.
Weave는 ChatNVIDIA python library에 대한 추적을 자동으로 캡처할 수 있습니다.원하는 프로젝트 이름으로 weave.init(<project-name>)를 호출하여 캡처를 시작하세요.
from langchain_nvidia_ai_endpoints import ChatNVIDIA
import weave
client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0.8, max_tokens=64, top_p=1)
# highlight-next-line
weave.init('emoji-bot')

messages=[
    {
      "role": "system",
      "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
    }]

response = client.invoke(messages)
chatnvidia_trace.png

자체 작업 추적하기

함수를 @weave.op로 래핑하면 입력, 출력 및 앱 로직을 캡처하여 데이터가 앱을 통해 어떻게 흐르는지 디버깅할 수 있습니다. 작업을 깊게 중첩하고 추적하려는 함수 트리를 구축할 수 있습니다. 또한 실험할 때 코드를 자동으로 버전 관리하여 git에 커밋되지 않은 임시 세부 정보를 캡처합니다.간단히 @weave.op로 장식된 함수를 만들어 ChatNVIDIA python library를 호출하세요.아래 예제에서는 op로 래핑된 2개의 함수가 있습니다. 이를 통해 RAG 앱의 검색 단계와 같은 중간 단계가 앱 동작에 어떤 영향을 미치는지 확인할 수 있습니다.
# highlight-next-line
import weave
from langchain_nvidia_ai_endpoints import ChatNVIDIA
import requests, random
PROMPT="""Emulate the Pokedex from early Pokémon episodes. State the name of the Pokemon and then describe it.
        Your tone is informative yet sassy, blending factual details with a touch of dry humor. Be concise, no more than 3 sentences. """
POKEMON = ['pikachu', 'charmander', 'squirtle', 'bulbasaur', 'jigglypuff', 'meowth', 'eevee']
client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0.7, max_tokens=100, top_p=1)

# highlight-next-line
@weave.op
def get_pokemon_data(pokemon_name):
    # highlight-next-line
    # This is a step within your application, like the retrieval step within a RAG app
    url = f"https://pokeapi.co/api/v2/pokemon/{pokemon_name}"
    response = requests.get(url)
    if response.status_code == 200:
        data = response.json()
        name = data["name"]
        types = [t["type"]["name"] for t in data["types"]]
        species_url = data["species"]["url"]
        species_response = requests.get(species_url)
        evolved_from = "Unknown"
        if species_response.status_code == 200:
            species_data = species_response.json()
            if species_data["evolves_from_species"]:
                evolved_from = species_data["evolves_from_species"]["name"]
        return {"name": name, "types": types, "evolved_from": evolved_from}
    else:
        return None

# highlight-next-line
@weave.op
def pokedex(name: str, prompt: str) -> str:
    # highlight-next-line
    # This is your root op that calls out to other ops
    # highlight-next-line
    data = get_pokemon_data(name)
    if not data: return "Error: Unable to fetch data"

    messages=[
            {"role": "system","content": prompt},
            {"role": "user", "content": str(data)}
        ]

    response = client.invoke(messages)
    return response.content

# highlight-next-line
weave.init('pokedex-nvidia')
# Get data for a specific Pokémon
pokemon_data = pokedex(random.choice(POKEMON), PROMPT)
Weave로 이동하여 UI에서 get_pokemon_data를 클릭하면 해당 단계의 입력 및 출력을 볼 수 있습니다.
nvidia_pokedex.png

더 쉬운 실험을 위해 Model를 생성하세요

여러 요소가 있을 때 실험을 구성하기는 어렵습니다. Model 클래스를 사용하면 시스템 프롬프트나 사용 중인 모델과 같은 앱의 실험적 세부 사항을 캡처하고 구성할 수 있습니다. 이를 통해 앱의 다양한 반복을 구성하고 비교할 수 있습니다.코드 버전 관리 및 입력/출력 캡처 외에도 Model는 애플리케이션 동작을 제어하는 구조화된 매개변수를 캡처하여 어떤 매개변수가 가장 효과적인지 쉽게 찾을 수 있게 합니다. Weave Models를 serve, 및 Evaluation와 함께 사용할 수도 있습니다.아래 예제에서는 modelsystem_message로 실험할 수 있습니다. 이 중 하나를 변경할 때마다 새로운 versionGrammarCorrectorModel를 얻게 됩니다.
import weave
from langchain_nvidia_ai_endpoints import ChatNVIDIA

weave.init('grammar-nvidia')

class GrammarCorrectorModel(weave.Model): # Change to `weave.Model`
  system_message: str

  @weave.op()
  def predict(self, user_input): # Change to `predict`
    client = ChatNVIDIA(model="mistralai/mixtral-8x7b-instruct-v0.1", temperature=0, max_tokens=100, top_p=1)

    messages=[
          {
              "role": "system",
              "content": self.system_message
          },
          {
              "role": "user",
              "content": user_input
          }
          ]

    response = client.invoke(messages)
    return response.content

corrector = GrammarCorrectorModel(
    system_message = "You are a grammar checker, correct the following user input.")
result = corrector.predict("That was so easy, it was a piece of pie!")
print(result)
chatnvidia_model.png

사용 정보

ChatNVIDIA 통합은 invoke, stream 및 비동기 변형을 지원합니다. 또한 도구 사용도 지원합니다. ChatNVIDIA는 다양한 유형의 모델과 함께 사용하기 위한 것이므로 함수 호출 지원이 없습니다.